import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from '@/common/filter';
import { ResponseIntercepotor } from '@/common/interceptor';
import { ValidationPipe } from '@nestjs/common';
import { BusinessException } from '@/common/excepetion';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 允许跨域
  app.enableCors();

  // 全局响应拦截器 处理返回格式
  app.useGlobalInterceptors(new ResponseIntercepotor());

  // 全局异常处理
  app.useGlobalFilters(new AllExceptionsFilter());

  // 全局参数验证
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: false,
      transform: true,

      // 👇 自定义异常格式
      exceptionFactory: (errors) => {
        const messages = errors.map((err) =>
          err.constraints ? Object.values(err.constraints).join(', ') : '',
        );
        return new BusinessException({ msg: messages.join(';') });
      },
    }),
  );

  await app.listen(process.env.PORT ?? 3000, '0.0.0.0');
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
bootstrap();
